import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
# from PyQt5.QtWidgets import QFileDialog, QMainWindow, QTreeWidgetItem, QApplication
from untitled import Ui_MainWindow
from MyThread import MyThread
from commonData import Data as data
import pandas
import os

class MyMainForm(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle(data.title + data.version)
        self.button_choice_file.clicked.connect(self.get_excel_folder)
        self.button_choice_put.clicked.connect(self.get_output_folder)
        self.button_star.clicked.connect(self.Star)
        self.button_end.clicked.connect(self.End)
        self.line_warmth.editingFinished.connect(self.get_alpha_warmth)
        self.line_cold.editingFinished.connect(self.get_alpha_cold)
        self.radioButton_north.toggled.connect(self.change_recent_north)
        self.radioButton_water.toggled.connect(self.change_recent_water)
        self.line_rain_num.editingFinished.connect(self.get_max_rain_num)
        self.checkBox_pd12.stateChanged.connect(self.change_pd12)
        self.checkBox_py12.stateChanged.connect(self.change_py12)
        self.line_put_file.editingFinished.connect(self.change_out_file)
        self.line_file.editingFinished.connect(self.change_file)
        self.line_rain_num.textChanged.connect(self.change_rain_num)
        self.radioButton_southwest.toggled.connect(self.get_recent_southwest)
        self.line_sw_a1.textChanged.connect(self.change_sw_a1)
        self.line_sw_a2.textChanged.connect(self.change_sw_a2)
        self.line_sw_turn_a.textChanged.connect(self.change_sw_turn_a)
        self.tree_sheet_name.itemChanged.connect(self.onclick)
        self.checkBox_user.stateChanged.connect(self.change_user_status)  # 更改用户自定义的状态
        self.button_user_file.clicked.connect(self.get_user_pdpy_file)


    def get_user_pdpy_file(self):
        fileName = QFileDialog.getOpenFileName(self, directory="C:", filter="*.xlsx")[0].replace("/", "\\")
        if fileName != "":
            self.line_user_file.setText(fileName)
            data.pdpy_excel_file = fileName

    def change_user_status(self):

        if self.checkBox_user.isChecked():  # 如果是选中的
            self.checkBox_pd12.setEnabled(False)
            self.checkBox_py12.setEnabled(False)
            self.line_user_file.setEnabled(True)
            self.button_user_file.setEnabled(True)
            data.user_value = True
        else:
            data.py_value = None
            data.pd_value = None
            self.checkBox_pd12.setEnabled(True)
            self.checkBox_py12.setEnabled(True)
            self.line_user_file.setEnabled(False)
            self.button_user_file.setEnabled(False)
            data.user_value = False


    def change_user_py(self):
        value = self.line_user_py.text()
        if self.checkBox_user.isChecked():
            if value != '':
                try:
                    data.py_value = float(value)
                    data.py12 = True
                except Exception as e:
                    print("自定义py有误，请查看格式是否正确,异常信息：", e)
        else:
            data.py_value = None



    def change_user_pd(self):
        value = self.line_user_pd.text()
        if self.checkBox_user.isChecked():   # 如果是在用户自定义的条件下输入了自定义值
            if value != '':
                try:
                    data.pd_value = float(value)
                    data.pd12 = True
                except Exception as e:
                    print("自定义py有误，请查看格式是否正确,异常信息：", e)
        else:
            data.pd_value = None  # 没选中则一律设置为None


    def onclick(self, item, state):
        info = item.text(0)
        if item.checkState(state) == Qt.Checked:
            data.names.append(info)
        else:
            if info in data.names:  # 如果未选中并且数据在内
                data.names.remove(info)

    def change_sw_turn_a(self): # 转换系数的
        try:
            num = float(self.line_sw_turn_a.text())
        except Exception:
            pass
        else:
            data.sw_turn_a = num


    def change_name(self):
        if self.checkBox_name1.isChecked():
            if self.checkBox_name1.text() not in data.names:
                data.names.append(self.checkBox_name1.text())
        else:
            if self.checkBox_name1.text() in data.names:
                data.names.remove(self.checkBox_name1.text())

        if self.checkBox_name2.isChecked():
            if self.checkBox_name2.text() not in data.names:
                data.names.append(self.checkBox_name2.text())
        else:
            if self.checkBox_name2.text() in data.names:
                data.names.remove(self.checkBox_name2.text())

        if self.checkBox_name3.isChecked():
            if self.checkBox_name3.text() not in data.names:
                data.names.append(self.checkBox_name3.text())
        else:
            if self.checkBox_name3.text() in data.names:
                data.names.remove(self.checkBox_name3.text())

    def change_sw_a1(self):
        try:
            num = float(self.line_sw_a1.text())
        except Exception:
            pass
        else:
            data.sw_a1 = num

    def change_sw_a2(self):
        try:
            num = float(self.line_sw_a2.text())
        except Exception:
            pass
        else:
            data.sw_a2 = num

    def change_rain_num(self):
        num = self.line_rain_num.text()
        data.pd_number = str(num)
        self.checkBox_py12.setText("Py" + str(num))
        self.checkBox_pd12.setText("Pd" + str(num))

    def change_file(self):
        fileName = self.line_put_file.text()
        self.line_file.setText(fileName)
        data.in_folder = fileName

    def change_out_file(self):
        fileName = self.line_put_file.text()
        self.line_put_file.setText(fileName)
        data.out_folder = fileName

    def change_pd12(self):
        if self.checkBox_pd12.isChecked():
            data.pd12 = True
        else:
            data.pd12 = False

    def change_py12(self):
        if self.checkBox_py12.isChecked():
            data.py12 = True
        else:
            data.py12 = False

    def get_max_rain_num(self):
        num = self.line_rain_num.text()
        if data.max_day_rain_num != float(num):
            data.max_day_rain_num = float(num)
            data.py_data, data.pd_data = {}, {}


    def get_recent_southwest(self):
        if self.radioButton_southwest.isChecked():
            data.recent = '西南大学模型'
            self.checkBox_user.setCheckState(0)
            data.user_value = False
            self.line_sw_a1.setEnabled(True)
            self.line_sw_a2.setEnabled(True)
            self.line_sw_turn_a.setEnabled(True)
            self.line_warmth.setEnabled(False)
            self.line_cold.setEnabled(False)
            self.checkBox_pd12.setEnabled(False)
            self.checkBox_py12.setEnabled(False)
            self.checkBox_user.setEnabled(False)
            self.button_user_file.setEnabled(False)
            self.line_user_file.setEnabled(False)

    def change_recent_water(self):
        if self.radioButton_water.isChecked():
            data.recent = '水利部门模型'
            self.checkBox_user.setCheckState(0)
            data.user_value = False
            self.line_warmth.setEnabled(True)
            self.line_cold.setEnabled(True)
            self.checkBox_pd12.setEnabled(False)
            self.checkBox_py12.setEnabled(False)
            self.line_sw_a1.setEnabled(False)
            self.line_sw_a2.setEnabled(False)
            self.line_sw_turn_a.setEnabled(False)
            self.checkBox_user.setEnabled(False)
            self.button_user_file.setEnabled(False)
            self.line_user_file.setEnabled(False)


    def change_recent_north(self):
        if self.radioButton_north.isChecked():
            data.recent = '北师大模型'
            self.checkBox_pd12.setEnabled(True)
            self.checkBox_py12.setEnabled(True)
            self.checkBox_user.setEnabled(True)
            self.checkBox_user.setEnabled(True)
            self.line_warmth.setEnabled(False)
            self.line_cold.setEnabled(False)
            self.line_sw_a1.setEnabled(False)
            self.line_sw_a2.setEnabled(False)
            self.line_sw_turn_a.setEnabled(False)




    def get_alpha_warmth(self):
        try:
            alpha = self.line_warmth.text()
            data.warmth = float(alpha)
        except Exception as e:
            print("输入暖季参数数字格式有误，请检查")



    def get_alpha_cold(self):
        alpha = self.line_cold.text()
        try:
            data.cold = float(alpha)
        except Exception as e:
            print("输入冷季参数数字格式有误，请检查")

    def get_excel_folder(self):  # 获取station的txt的文件夹所在的位置
        fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace("/", "\\")  # 获取气温所在的文件夹的位置
        if fileName != '':
            data.py_data, data.pd_data, data.dict_of_all_excel = {}, {}, {}  # 重新更新三个基本变量
            data.in_folder = fileName
            self.line_file.setText(fileName)
            data.out_folder = fileName[:2] + "\\" + "模型计算结果"  # 默认放在G盘
            self.line_put_file.setText(data.out_folder)
            file = os.listdir(fileName)[0]
            wb = pandas.ExcelFile(fileName + "\\" + file)
            temp = []
            data.names = []     # 重置data.names
            self.tree_sheet_name.clear()
            for name in wb.sheet_names:
                if name not in temp:
                    temp.append(name)

            for name in temp:
                root = QTreeWidgetItem(self.tree_sheet_name)
                root.setText(0, name)
                root.setCheckState(0, Qt.Unchecked)



    def get_output_folder(self):
        fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace("/", "\\")  # 获取气温所在的文件夹的位置
        print(data.out_folder)
        if fileName != '':
            data.out_folder = fileName
            self.line_put_file.setText(fileName)
        print(data.out_folder)

    def Star(self):
        self.thread = MyThread()
        # try:
        if len(data.names) == 0:
            print("看起来没有选中任何表，请检查再做处理。")
        else:
            self.thread.start()  # start调用的是run
        # except Exception as e:
        #     print("输入信息有误或是无有效输入!\n\n异常信息: ", "", e)
    def End(self):
        sys.exit(app.exec_())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())
